<?php

class Newsletter extends Front_Controller {
	 
	function __construct()
	{
		parent::__construct();
		$this->load->library('form_validation');
		$this->load->model('newsletter_model');
	}
	function index()
	{
		$this->form_validation->set_rules('nom', 'nom', 'trim|xss_clean|max_length[50]');
		$this->form_validation->set_rules('email', 'email', 'required|trim|xss_clean|valid_email|is_unique[newsletter.email]|max_length[500]');
			
		$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');

		if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		{
			$this->load->view('newsletter');
		}
		else // passed validation proceed to post success logic
		{
			// build array for the model
				
			$form_data = array(
					'nom' => set_value('nom'),
					'email' => set_value('email'),
					'ip'=>$this->input->ip_address()
			);
				
			// run insert model to write data to db

			if ($this->newsletter_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
			{
				redirect('newsletter/success');   // or whatever logic needs to occur
			}
			else
			{
				echo 'An error occurred saving your information. Please try again later';
				// Or whatever error handling is necessary
			}
		}
	}
	function success()
	{
		
			$data=array('message_success'=> 'Votre demande est bien enregistrée');

			$this->load->view('unsubscribe',$data);
	}
	function unsubscribe()
	{
		$this->form_validation->set_rules('email', 'email', 'required|trim|xss_clean|valid_email|max_length[500]');
			
		$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
		$data=array();
		if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		{
			$this->load->view('unsubscribe');
		}
		else // passed validation proceed to post success logic
		{
			// run delete model to write data to db
			$data['message_success']='Votre demande désabonnement est bien enregistrée';
			$check=$this->newsletter_model->Delete(set_value('email')); 
			if(!$check)
				$data['message_success']='Votre email '.set_value('email').' ne trouve pas dans notre système';
		}
		$this->load->view('unsubscribe',$data);
	}
}